import json
import falcon
import logging
from masking import ModelDocLocalisation

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class DocLocalisationResource(ModelDocLocalisation):
    """
    @params:
        req : The data sent in the request
        resp : This contains the response which will be given when end-point is called
    """

    def __init__(self, doc_localisation_model):
        ModelDocLocalisation.__init__(self, doc_localisation_model)

    def on_post(self, req, resp):
        try:
            request = json.loads(req.stream.read())
        except Exception as e:
            logger.error('Malformed JSON')
            raise falcon.HTTPBadRequest(title="Malformed JSON")

        if "doc_url" in request:
            doc_url = request["doc_url"]
        else:
            logger.error('Document URL not present')
            raise falcon.HTTPBadRequest(title="Invalid JSON")

        if doc_url.replace(" ", "") == "":
            logger.error('Document URL not present')
            raise falcon.HTTPBadRequest(title="URL is invalid")
        else:
            logger.info('Processing Request')
            localized_doc = self.get_doc_mask(doc_url)

            resp.body = json.dumps(localized_doc)
            resp.status = falcon.HTTP_200
            logger.info("Requested Processed Successfully")
